/**
 * DI 容器重构示例
 * 
 * 展示如何将单例模式重构为依赖注入
 * 
 * @author AI Assistant
 * @date 2025-11-27
 */

import { container, ServiceLifetime } from './DIContainer';
import { Injectable, Inject, ServiceIdentifiers } from './Decorators';
import { Log } from '../logger/LoggerGlobal';

// ============================================================================
// 示例 1: 重构简单单例 -> DI
// ============================================================================

/**
 * ❌ 重构前：传统单例
 */
class OldConfigManagerSingleton {
    private static instance: OldConfigManagerSingleton | null = null;
    private config: Record<string, any> = {};
    
    private constructor() {
        this.loadConfig();
    }
    
    static getInstance(): OldConfigManagerSingleton {
        if (!this.instance) {
            this.instance = new OldConfigManagerSingleton();
        }
        return this.instance;
    }
    
    private loadConfig(): void {
        // 加载配置
    }
    
    getConfig(key: string): any {
        return this.config[key];
    }
}

/**
 * ✅ 重构后：使用 DI 容器（方式1：手动注册）
 */
export class ConfigManager {
    private config: Record<string, any> = {};
    
    constructor() {
        this.loadConfig();
        Log.general.debug('ConfigManager 已创建');
    }
    
    private loadConfig(): void {
        // 加载配置
    }
    
    getConfig(key: string): any {
        return this.config[key];
    }
    
    destroy(): void {
        this.config = {};
        Log.general.debug('ConfigManager 已销毁');
    }
}

// 注册到容器（在应用启动时）
// container.registerSingleton(ServiceIdentifiers.ConfigManager, ConfigManager);

// 使用
// const configManager = container.resolve<ConfigManager>(ServiceIdentifiers.ConfigManager);

/**
 * ✅ 重构后：使用 DI 容器（方式2：装饰器自动注册）
 */
@Injectable(ServiceLifetime.SINGLETON, ServiceIdentifiers.ConfigManager)
export class ConfigManagerWithDecorator {
    private config: Record<string, any> = {};
    
    constructor() {
        this.loadConfig();
        Log.general.debug('ConfigManager 已创建（装饰器）');
    }
    
    private loadConfig(): void {
        // 加载配置
    }
    
    getConfig(key: string): any {
        return this.config[key];
    }
    
    destroy(): void {
        this.config = {};
    }
}

// 使用（自动注册）
// const configManager = container.resolve<ConfigManagerWithDecorator>(ServiceIdentifiers.ConfigManager);

// ============================================================================
// 示例 2: 重构带依赖的单例 -> DI
// ============================================================================

/**
 * ❌ 重构前：单例之间互相依赖
 */
class OldLoggerSingleton {
    private static instance: OldLoggerSingleton | null = null;
    
    private constructor() {}
    
    static getInstance(): OldLoggerSingleton {
        if (!this.instance) {
            this.instance = new OldLoggerSingleton();
        }
        return this.instance;
    }
    
    log(message: string): void {
        console.log(message);
    }
}

class OldServiceWithDependency {
    private static instance: OldServiceWithDependency | null = null;
    private logger: OldLoggerSingleton;
    
    private constructor() {
        // 硬编码依赖
        this.logger = OldLoggerSingleton.getInstance();
    }
    
    static getInstance(): OldServiceWithDependency {
        if (!this.instance) {
            this.instance = new OldServiceWithDependency();
        }
        return this.instance;
    }
    
    doSomething(): void {
        this.logger.log('Doing something');
    }
}

/**
 * ✅ 重构后：使用 DI 容器 + 构造函数注入
 */
export class LoggerService {
    log(message: string): void {
        Log.general.info(message);
    }
    
    destroy(): void {
        Log.general.debug('LoggerService 已销毁');
    }
}

export class ServiceWithDependency {
    constructor(private logger: LoggerService) {
        Log.general.debug('ServiceWithDependency 已创建');
    }
    
    doSomething(): void {
        this.logger.log('Doing something');
    }
    
    destroy(): void {
        Log.general.debug('ServiceWithDependency 已销毁');
    }
}

// 注册
// container.registerSingleton(ServiceIdentifiers.Logger, LoggerService);
// container.registerSingleton('ServiceWithDependency', ServiceWithDependency, [ServiceIdentifiers.Logger]);

// 使用
// const service = container.resolve<ServiceWithDependency>('ServiceWithDependency');
// service.doSomething();

/**
 * ✅ 重构后：使用装饰器 + 属性注入
 */
@Injectable(ServiceLifetime.SINGLETON, ServiceIdentifiers.Logger)
export class LoggerServiceDecorator {
    log(message: string): void {
        Log.general.info(message);
    }
}

@Injectable(ServiceLifetime.SINGLETON)
export class ServiceWithPropertyInjection {
    @Inject(ServiceIdentifiers.Logger)
    private logger!: LoggerServiceDecorator;
    
    constructor() {
        Log.general.debug('ServiceWithPropertyInjection 已创建');
    }
    
    doSomething(): void {
        this.logger.log('Doing something with property injection');
    }
}

// ============================================================================
// 示例 3: 重构 GameApplication -> DI
// ============================================================================

/**
 * ✅ GameApplication 使用 DI
 */
@Injectable(ServiceLifetime.SINGLETON, ServiceIdentifiers.GameApplication)
export class GameApplicationDI {
    @Inject(ServiceIdentifiers.SceneCoordinator)
    private sceneCoordinator!: any;
    
    @Inject(ServiceIdentifiers.ECSWorld)
    private ecsWorld!: any;
    
    @Inject(ServiceIdentifiers.Logger)
    private logger!: LoggerService;
    
    constructor() {
        Log.game.debug('GameApplication 已创建（DI）');
    }
    
    async initialize(): Promise<void> {
        this.logger.log('初始化游戏应用');
        // 初始化逻辑
    }
    
    start(): void {
        this.logger.log('启动游戏');
        // 启动逻辑
    }
    
    destroy(): void {
        Log.game.debug('GameApplication 已销毁');
    }
}

// ============================================================================
// 示例 4: 工厂函数注册
// ============================================================================

/**
 * 使用工厂函数注册复杂服务
 */
export class DatabaseConnection {
    constructor(private connectionString: string) {
        Log.general.debug('DatabaseConnection 已创建', { connectionString });
    }
    
    connect(): void {
        Log.general.info('数据库已连接');
    }
    
    destroy(): void {
        Log.general.debug('DatabaseConnection 已销毁');
    }
}

// 使用工厂函数注册
// container.registerSingleton('DatabaseConnection', (container) => {
//     const config = container.resolve<ConfigManager>(ServiceIdentifiers.ConfigManager);
//     const connectionString = config.getConfig('database.connectionString');
//     return new DatabaseConnection(connectionString);
// });

// ============================================================================
// 示例 5: 作用域服务
// ============================================================================

/**
 * HTTP 请求作用域服务
 */
@Injectable(ServiceLifetime.SCOPED)
export class RequestContext {
    private requestId: string;
    
    constructor() {
        this.requestId = Math.random().toString(36).substr(2, 9);
        Log.general.debug('RequestContext 已创建', { requestId: this.requestId });
    }
    
    getRequestId(): string {
        return this.requestId;
    }
}

/**
 * 使用请求上下文的服务
 */
@Injectable(ServiceLifetime.SCOPED)
export class RequestService {
    @Inject()
    private context!: RequestContext;
    
    processRequest(): void {
        Log.general.info('处理请求', {
            requestId: this.context.getRequestId()
        });
    }
}

// 使用
// const scope = container.createScope();
// const service1 = scope.resolve<RequestService>(RequestService);
// const service2 = scope.resolve<RequestService>(RequestService);
// // service1 和 service2 的 context 是同一个实例
// scope.clearScope();

// ============================================================================
// 示例 6: 完整的应用启动流程
// ============================================================================

/**
 * 应用启动器
 */
export class Application {
    /**
     * 配置容器
     */
    static configureServices(): void {
        Log.styled('━'.repeat(60), 'separator');
        Log.styled('📦 配置 DI 容器', 'title');
        Log.styled('━'.repeat(60), 'separator');
        
        // 方式1：手动注册
        container.registerSingleton(ServiceIdentifiers.Logger, LoggerService);
        container.registerSingleton(ServiceIdentifiers.ConfigManager, ConfigManager);
        
        // 方式2：工厂函数
        container.registerSingleton('DatabaseConnection', (c) => {
            const config = c.resolve<ConfigManager>(ServiceIdentifiers.ConfigManager);
            return new DatabaseConnection(config.getConfig('db') || 'localhost');
        });
        
        // 方式3：依赖注入
        container.registerSingleton(
            'ServiceWithDependency',
            ServiceWithDependency,
            [ServiceIdentifiers.Logger]
        );
        
        Log.styled('✅ 服务配置完成', 'success');
        container.printStatistics();
    }
    
    /**
     * 启动应用
     */
    static async start(): Promise<void> {
        Log.styled('━'.repeat(60), 'separator');
        Log.styled('🚀 启动应用', 'title');
        Log.styled('━'.repeat(60), 'separator');
        
        // 配置服务
        this.configureServices();
        
        // 解析并启动游戏应用
        const gameApp = container.resolve<GameApplicationDI>(ServiceIdentifiers.GameApplication);
        await gameApp.initialize();
        gameApp.start();
        
        Log.styled('✅ 应用启动完成', 'success');
        Log.styled('━'.repeat(60), 'separator');
    }
    
    /**
     * 停止应用
     */
    static stop(): void {
        Log.styled('━'.repeat(60), 'separator');
        Log.styled('🛑 停止应用', 'title');
        Log.styled('━'.repeat(60), 'separator');
        
        // 清理容器
        container.clear();
        
        Log.styled('✅ 应用已停止', 'success');
        Log.styled('━'.repeat(60), 'separator');
    }
}

// ============================================================================
// 使用示例
// ============================================================================

/**
 * 运行所有示例
 */
export async function runDIExamples(): Promise<void> {
    Log.styled('━'.repeat(60), 'separator');
    Log.styled('🔧 DI 容器示例', 'title');
    Log.styled('━'.repeat(60), 'separator');
    
    // 配置服务
    Application.configureServices();
    
    // 示例1：解析简单服务
    Log.styled('📚 示例 1: 解析简单服务', 'large');
    const config = container.resolve<ConfigManager>(ServiceIdentifiers.ConfigManager);
    Log.general.info('ConfigManager 已解析');
    
    // 示例2：解析带依赖的服务
    Log.styled('📚 示例 2: 解析带依赖的服务', 'large');
    const service = container.resolve<ServiceWithDependency>('ServiceWithDependency');
    service.doSomething();
    
    // 示例3：工厂函数
    Log.styled('📚 示例 3: 工厂函数', 'large');
    const db = container.resolve<DatabaseConnection>('DatabaseConnection');
    db.connect();
    
    // 示例4：作用域服务
    Log.styled('📚 示例 4: 作用域服务', 'large');
    const scope = container.createScope();
    const req1 = scope.resolve<RequestService>(RequestService);
    const req2 = scope.resolve<RequestService>(RequestService);
    req1.processRequest();
    req2.processRequest();
    scope.clearScope();
    
    // 打印统计
    container.printStatistics();
    
    Log.styled('━'.repeat(60), 'separator');
    Log.styled('✅ 所有示例运行完成', 'success');
    Log.styled('━'.repeat(60), 'separator');
}

